package com.example.camera.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.TextureView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class AutoFitTextureView extends TextureView {

    private int mRationWidth = 0;

    private int mRationHeight = 0;

    public AutoFitTextureView(@NonNull Context context) {
        super(context);
    }

    public AutoFitTextureView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

    }

    public AutoFitTextureView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setAspectRatio(int width,int height){
        mRationHeight = height;
        mRationWidth =width;
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if(0 == mRationWidth || 0 == mRationHeight){
            setMeasuredDimension(width,height);
        }else{
            if(width < height * mRationWidth / mRationHeight){
                setMeasuredDimension(width,width * mRationHeight / mRationWidth);
            }
            else {
                setMeasuredDimension(height * mRationWidth / mRationHeight,height);
            }
        }
    }
}
